package com.crocodileq.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.crocodileq.dto.Result;
import com.crocodileq.entity.ShopType;
import com.crocodileq.mapper.ShopTypeMapper;
import com.crocodileq.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crocodileq.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Result queryTypeList() {
        //1、查询缓存
        List<String> cacheTypeList = stringRedisTemplate.opsForList()
                .range(RedisConstants.CACHE_SHOP_TYPE_KEY, 0, -1);

        //2、缓存存在，直接返回
        if (CollUtil.isNotEmpty(cacheTypeList)) {
            //反序列化
            List<ShopType> resultTypeList = cacheTypeList.stream()
                    .map(item -> JSON.parseObject(item, ShopType.class))
                    .collect(Collectors.toList());
            // 缓存存在且有数据，可以直接返回
            return Result.ok(resultTypeList);
        }
        //3、缓存不存在，查询数据库
        List<ShopType> dbTypeList = query().orderByAsc("sort").list();

        //4、数据库不存在，返回错误 404
        if (CollUtil.isEmpty(dbTypeList)) {
            // 数据库不存在，返回错误 404
            return Result.fail("店铺类型不存在");
        }
        List<String> strTypeList = dbTypeList.stream().map(JSON::toJSONString).collect(Collectors.toList());

        //5、数据库存在，写入缓存
        stringRedisTemplate.opsForList().leftPushAll(RedisConstants.CACHE_SHOP_TYPE_KEY, strTypeList);
        //添加有效期
        stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_TYPE_KEY, RedisConstants.CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);

        //6、返回数据
        return Result.ok(dbTypeList);
    }
}
